package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.customer.mapper.BankAccountMapper;
import com.jzo2o.customer.model.domain.BankAccount;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.dto.request.BankAccountUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.BankAccountResDTO;
import com.jzo2o.customer.service.IBankAccountService;
import com.jzo2o.customer.service.IServeProviderService;
import com.jzo2o.mvc.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 银行账户信息表 服务实现类
 * </p>
 *
 * @author liush
 * @since 2024-12-13
 */
@Slf4j
@Service
public class BankAccountServiceImpl extends ServiceImpl<BankAccountMapper, BankAccount> implements IBankAccountService {

    @Resource
    private IServeProviderService serveProviderService;

    @Override
    public BankAccountResDTO currentUserBankAccount() {
        //查询当前登录用户的银行账户信息
        BankAccount bankAccount = getById(UserContext.currentUserId());
        //返回银行账户信息
        return BeanUtil.copyProperties(bankAccount, BankAccountResDTO.class);
    }

    @Override
    public void addOrUpdate(BankAccountUpsertReqDTO dto) {
        //如果请求参数为空，抛出异常提示请求参数不合法
        if (dto==null){
            throw new BadRequestException("请求参数不合法！！");
        }

        //封装新账户信息
        BankAccount newBankAccount = BeanUtil.copyProperties(dto, BankAccount.class);
        //设置用户id为当前登录用户id
        newBankAccount.setId(UserContext.currentUserId());

        //查询用户类型
        ServeProvider serveProvider = serveProviderService.lambdaQuery()
                .eq(ServeProvider::getId, UserContext.currentUserId())
                .one();

        //设置用户类型
        newBankAccount.setType(serveProvider.getType());

        //查询当前用户的银行账户信息
        BankAccount oldBankAccount = getById(UserContext.currentUserId());
        //判断是否已存在，如果不存在则新增，如果存在则修改
        if (oldBankAccount==null){
            boolean result = save(newBankAccount);
            if (!result){
                log.info("用户id为{}的服务机构用户新增银行账户信息失败，银行账户信息为{}",UserContext.currentUserId(), newBankAccount);
                throw new CommonException("新增银行账户信息失败！！");
            }
        }else {
            boolean result = updateById(newBankAccount);
            if (!result){
                log.info("用户id为{}的服务机构用户修改银行账户信息失败，银行账户信息为{}",UserContext.currentUserId(), newBankAccount);
                throw new CommonException("修改银行账户信息失败！！");
            }
        }
    }
}
